const sql = require('mssql');
// const baseFn = require('../../public/base.js');



//  保存菜单信息
const saveMenu = async (ctx, next) => {
    try {
        let body = ctx.request.body;
        let { MC, PX, LJ, MS } = body.formList;
        let saveMenuSql = '';
        if (body.menuId) {
            saveMenuSql = ` UPDATE CDGL SET MC = '${MC}',PX = '${PX}',LJ = '${LJ}',MS = '${MS}' WHERE ID = ${body.menuId} `;
        } else {
            saveMenuSql = ` INSERT INTO CDGL (MC,PX,LJ,MS,GLID,ZT) VALUES ('${MC}',${PX},
        '${LJ}','${MS}',${body.relationId},'T') `;
        }
        let result = await sql.query(saveMenuSql);
        if (result.rowsAffected > 0) {
            ctx.body = {
                code: 200,
                message: '保存成功',
                result: true
            }
        } else {
            ctx.body = {
                code: 400,
                message: '保存失败',
                result: false
            }
        }

    } catch (err) {
        ctx.body = { code: 500, message: '服务器错误', result: err }

    }
}

// 递归菜单列表
const formatMenu = (result, id) => {
    let menuList = result.filter(item => {
        return item.GLID == id;
    });
    if (0 in menuList) {
        menuList.forEach(item => {
            let itemMenuList = formatMenu(result, item.ID);
            if (0 in itemMenuList) {
                item.children = itemMenuList;
            }
        });
    }
    return menuList;
};

//  获取菜单信息
const getMenuList = async (ctx, next) => {
    try {
        let body = ctx.request.query;
        console.log(body);
        let selectSql = ` SELECT *   `;
        if (body.userId) {
            selectSql += ` ,CASE WHEN CD.ID IN (SELECT QX.CDID FROM QXGL QX WHERE QX.BM = '${body.userId}' AND ZT = 'T') THEN 'T' ELSE 'F' END AS QXZT `;
        }
        selectSql += ` FROM CDGL CD `;
        let result = await sql.query(selectSql);
        if (result.rowsAffected > 0) {
            ctx.body = {
                code: 200,
                message: '获取成功',
                result: formatMenu(result.recordset, 0)
            }
        } else {
            ctx.body = {
                code: 400,
                message: '获取失败',
                result: []
            }
        }
    } catch (err) {
        ctx.body = { code: 500, message: '服务器错误', result: err }

    }


}

//  获取单个菜单信息
const getSingleMenu = async (ctx, next) => {
    try {
        let { id } = ctx.request.query;
        let selectSql = ` SELECT * FROM CDGL WHERE ID=${id} `;

        let result = await sql.query(selectSql);
        if (result.rowsAffected > 0) {
            ctx.body = {
                code: 200,
                message: '保存成功',
                result: result.recordset[0]
            }
        } else {
            ctx.body = {
                code: 400,
                message: '保存失败',
                result: {}
            }
        }
    } catch (err) {
        ctx.body = { code: 500, message: '服务器错误', result: err }

    }


}

//  移动菜单
const saveMoveMenu = async (ctx, next) => {
    try {

        let { ID, GLID } = ctx.request.body;
        let updateSql = `UPDATE CDGL SET GLID = ${GLID} WHERE ID=${ID} `;

        let result = await sql.query(updateSql);
        if (result.rowsAffected > 0) {
            ctx.body = {
                code: 200,
                message: '移动成功',
                result: true
            }
        } else {
            ctx.body = {
                code: 400,
                message: '移动失败',
                result: false
            }
        }
    } catch (err) {
        ctx.body = { code: 500, message: '服务器错误', result: err }

    }


}

//  改变菜单的状态
const changeMenuState = async (ctx, next) => {
    try {
        console.log(ctx.request.body);
        let { ZT, ID } = ctx.request.body;
        let updateSql = `UPDATE CDGL SET ZT = '${ZT}' WHERE ID=${ID} `;

        let result = await sql.query(updateSql);
        if (result.rowsAffected > 0) {
            ctx.body = {
                code: 200,
                message: '保存成功',
                result: true
            }
        } else {
            ctx.body = {
                code: 400,
                message: '保存失败',
                result: false
            }
        }
    } catch (err) {
        ctx.body = { code: 500, message: '服务器错误', result: err }

    }


}


//  保存用户权限
const saveUserPermission = async (ctx, next) => {

    try {
        console.log(ctx.request.body);
        let { userId, menuList } = ctx.request.body;
        let actionSqlList = [];
        if (0 in menuList) {
            let idStr = menuList.join(',');
            let updateAllSql = ` update QXGL SET ZT = 'F' WHERE BM = '${userId}' AND  CDID not in (${idStr})`;
            actionSqlList.push(updateAllSql);
            for (let item of menuList) {
                let isExistResult = await sql.query(`SELECT COUNT(BM) AS TOTAL FROM QXGL WHERE BM = '${userId}' AND CDID= ${item}`);
                let isExist = isExistResult.recordset[0].TOTAL;
                if (isExist > 0) {
                    let updatePartSql = ` update QXGL SET ZT = 'T' WHERE BM = '${userId}' AND  CDID = ${item} `;
                    actionSqlList.push(updatePartSql);
                } else {
                    let insertSql = ` INSERT INTO QXGL(BM,CDID,ZT) VALUES('${userId}',${item},'T')  `;
                    actionSqlList.push(insertSql);
                }
            }
        } else {
            actionSqlList.push(` update QXGL SET ZT = 'F' WHERE BM = '${userId}'  `);
        }
        let lastSql = ` SET XACT_ABORT ON Begin Tran ${actionSqlList.join(' ')} Commit Tran `;
        console.log('lastSql', lastSql);
        let result = await sql.query(lastSql);
        let isSuccess = result.rowsAffected.some(item => item > 0);
        console.log(result);
        if (isSuccess) {
            ctx.body = {
                code: 200,
                message: '授权成功',
                result: true
            }
        } else {
            ctx.body = {
                code: 400,
                message: '授权失败',
                result: false
            }
        }
    } catch (err) {
        ctx.body = { code: 500, message: '服务器错误', result: err }

    }


}








module.exports = {
    'POST /saveMenu': saveMenu,
    'POST /saveUserPermission': saveUserPermission,
    'POST /saveMoveMenu': saveMoveMenu,
    'POST /changeMenuState': changeMenuState,
    'GET /getSingleMenu': getSingleMenu,
    'GET /getMenuList': getMenuList
}
